﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using CommandType = Library.CommandType;
using Library;
using System.Threading;
using System.Net;
namespace ClientFrm
{
    public partial class WaitingFrm : Form
    {
        bool Playing = false;
        Thread TTchayFrmPlays;
        private string _userName;
        private Socket _clientSocket;
        private byte[] _buffer;
        List<GroupBox> DSBan;
        List<GroupBox> DSPlayer = new List<GroupBox>();

        public WaitingFrm()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
        }
        void CauHinhSocKet()
        {
            _clientSocket = new Socket(AddressFamily.InterNetwork,
               SocketType.Stream, ProtocolType.Tcp);
            var ip = IPAddress.Parse("127.0.0.1");
            var serverEp = new IPEndPoint(ip, 5555);

            _clientSocket.BeginConnect(serverEp,
                                      null, null);
        }
        void LayDsBan()
        {
            DSBan = panelPhong.Controls.Cast<Control>().Where(x => x is GroupBox && x.Tag != null).Cast<GroupBox>().ToList();
            foreach (var item in DSBan)
            {

            }
        }
        private void WaitingFrm_Load(object sender, EventArgs e)
        {
            LayDsBan();
            CauHinhSocKet();
               this.Hide();
            var dialog = new LoginFrm();
            if (dialog.ShowDialog() == DialogResult.OK)
            {

                _userName = dialog.UserName;
                lbTenNgChoi.Text = _userName;
                this.Text = _userName;
                _buffer = new byte[2048];
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                           SocketFlags.None, OnMessageReceived, null);

                
                //TTchayFrmPlays.Start();
            }
            else this.Close();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (_clientSocket != null)
            {
                var msg = new ChatMessage()
                {
                    CmdType = CommandType.ClientOut,

                    SenderName = _userName,
                    MsgBody = "quit"


                };
                SendMessage(msg);
                Thread.Sleep(100);

                _clientSocket.Shutdown(SocketShutdown.Both);
                _clientSocket.Close();
            }
        }
        ChatMessage recvMsg;
        public List<ListViewItem> LayDSThanhVien()//lay danh sach thanh vien tu listview
        {
            return listViewDsThanhVien.Items.Cast<ListViewItem>().ToList();
        }
        void UPdatePlayer()
        {
            var dsthanhvien = LayDSThanhVien();
            var item = dsthanhvien.Find(x => x.Text == recvMsg.SenderName);
            item.SubItems[1].Text = recvMsg.MsgBody.ToString();
        }
        void RemovePlayer()
        {
            var dsthanhvien = listViewDsThanhVien.Items;
            var item = dsthanhvien.Cast<ListViewItem>().ToList().Find(x => x.Text == recvMsg.SenderName);
            dsthanhvien.Remove(item);
            listViewDsThanhVien.Refresh();
        }
        void InsertPlayer()
        {
            var dsthanhvien = listViewDsThanhVien.Items;
            dsthanhvien.Add(new ListViewItem(
                             new string[] { recvMsg.SenderName, "Waiting" }
                            ));
        }
        void LoadPlayer(ChatMessage rev)
        {
            var dsthanhvien = listViewDsThanhVien.Items;
            dsthanhvien.Clear();
            foreach (var item in (rev.MsgBody as List<ThongTinNguoiChoi>))
            {
                dsthanhvien.Add(new ListViewItem(
                     new string[] { item.UserName, item.Ban > 0 ? "Playing" : "Waiting" }
                     ));
            }

        }
        public List<GroupBox> LayDSPlayerTrongTrenBan(int ban)
        {
            var groupban=DSBan.Find(x=>x.Tag!=null&&x.Tag.ToString()==ban.ToString());
            return groupban.Controls.Cast<Control>().ToList().
                FindAll(x => x.Text == ""&&x.Tag!=null&&x.Tag.ToString()=="player").Cast<GroupBox>().ToList();
        }
        void UpdateNewJoiner(int Ban,string username)
        {
            var dsplayer= LayDSPlayerTrongTrenBan(Ban);
            if (dsplayer.Count>0&&Ban >= 1 && Ban <= 6)
            {
                var player = dsplayer[0];
                var pb = player.Controls.Cast<Control>().
                    ToList().Find(x => x is PictureBox) as PictureBox;
                pb.Image = imageListPlayer.Images[0];
                DSPlayer.Add(player);
            }

        }
        private void OnMessageReceived(IAsyncResult ar)
        {
            try
            {
                _clientSocket.EndReceive(ar);

                recvMsg = new ChatMessage(_buffer);


                if (recvMsg.CmdType != CommandType.ClientOut && _userName == recvMsg.SenderName)
                {
                    _buffer = new byte[2000];
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                            SocketFlags.None, OnMessageReceived, null);
                }
            


                switch (recvMsg.CmdType)
                {
                    case CommandType.ClientLogin:
                        InsertPlayer();
                        break;

                    case CommandType.Message:
                        listViewSendMessage.Items.Add(
                            new ListViewItem(
                                new string[] { recvMsg.SenderName, recvMsg.MsgBody.ToString() }
                                ));
                        break;

                    case CommandType.ClientOut:
                        RemovePlayer();
                        break;
                    case CommandType.VaoBan:
                    //case CommandType.RaKhoiBan:
                    //    UPdatePlayer();
                    //    break;
                    //case CommandType.ThongTinBan:
                    //   // Playing = true;
                    //    //TTchayFrmPlays = new Thread(DangChoi);
                    //  //  TTchayFrmPlays.Start();
                    //     //PlaysFrm playfrm = new PlaysFrm(_clientSocket,_userName,recvMsg);



                    //     //if (playfrm.ShowDialog(this) == DialogResult.OK)
                    //     //{
                    //     //    var msg1 = new ChatMessage()
                    //     //    {

                    //     //        SenderName = _userName,
                    //     //        MsgBody = "-1",
                    //     //        CmdType = CommandType.RaKhoiBan
                    //     //    };
                    //     //    SendMessage(msg1);
                    //   //  }
                    //    break;
                    case CommandType.HuyLenh:
                        MessageBox.Show(recvMsg.MsgBody.ToString());
                        break;
                }

              
            }
            catch (Exception ex)
            {
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                             SocketFlags.None,
                                             OnMessageReceived, null);
                MessageBox.Show(ex.Message);
            }
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMessage.Text))
            {
                MessageBox.Show("chua nhap thong diep ", "loi ");
                return;
            }
            listViewSendMessage.Items.Add(
                new ListViewItem(new[] { _userName, txtMessage.Text, }));
            var msg = new ChatMessage()
            {

                SenderName = _userName,
                MsgBody = txtMessage.Text,

                CmdType = CommandType.Message


            };
            SendMessage(msg);

            txtMessage.Text = "";
        }
        void SendMessage(ChatMessage msg)
        {
            var buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length,
                                SocketFlags.None, OnMessageSent, null);
        }
        private void OnMessageSent(IAsyncResult ar)
        {
            try
            {
                _clientSocket.EndSend(ar);
            }
            catch
            {
                DialogResult = DialogResult.Cancel;
            }
        }


        private void txtMessage_KeyDown(object sender, KeyEventArgs e)
        {
            DialogResult = DialogResult.OK;
            if (e.KeyCode == Keys.Enter)
                btnSend.PerformClick();
        }
        private void btnVaoBan_Click(object sender, EventArgs e)
        {
            Button bt = sender as Button;
            ChatMessage msg = new ChatMessage()
            {
                CmdType = CommandType.VaoBan,

                SenderName = _userName,
                MsgBody = bt.Parent.Text[bt.Parent.Text.Length - 1].ToString()

            };
            SendMessage(msg);
           // Thread.Sleep(100);
        }
        Semaphore sm = new Semaphore(2, 2);
        void DangChoi()
        {

            //sm.WaitOne();
            //Thread.Sleep(100);
            //  sm.Release();

            // Playing = false;
            //if (recvMsg.SenderName == _userName)
            //{
            //this.Hide();
            //if (Playing)
            //{
                PlaysFrm playfrm = new PlaysFrm();



                if (playfrm.ShowDialog(this) == DialogResult.OK)
                {
                    var msg1 = new ChatMessage()
                    {

                        SenderName = _userName,
                        MsgBody = "-1",
                        CmdType = CommandType.BatDauChoi
                    };
                    SendMessage(msg1);

                }
                //TTchayFrmPlays.Abort();




            //}
        }
        
    }
}
